<template>
    <slot :formatTime="formatTime"
          :currentTime="currentTime"
          :formatFunc="formatFunc">
        {{formatTime}}
    </slot>
</template>

<script setup>
    import {
        ref, watch, defineProps,
        computed, defineEmits, defineExpose,
        onBeforeUnmount, onMounted
    } from 'vue'

    const props = defineProps({
        time: Number,
        autoStart: {
            type: Boolean,
            default: false
        }
    })
    const emit = defineEmits(['change', 'finish'])

    const currentTime = ref(props.time)
    let interval = null //秒级计时器
    const formatTime = computed(() => {
        return formatFunc(currentTime.value)
    })
    const formatFunc = (currentTime, format_str = '%h:%m:%s') => {
        let h = 0 | currentTime / 3600
        let m = 0 | (currentTime % 3600) / 60
        let s = 0 | (currentTime % 3600) % 60
        return format_str.replace('%h', h < 10 ? '0' + h : h).replace('%m', m < 10 ? '0' + m : m).replace('%s', s < 10 ? '0' + s : s)
        // return {
        //     h: h < 10 ? '0' + h : h,
        //     m: m < 10 ? '0' + m : m,
        //     s: s < 10 ? '0' + s : s,
        // }
    }
    const start = () => {
        interval = setInterval(() => {
            currentTime.value -= 1
            if (currentTime.value <= 0) {
                clearInterval(interval)//销毁计时器
                emit('finish')
            }
        }, 1000)
    }
    const pause = () => {
        clearInterval(interval)//销毁计时器
    }
    const reset = () => {
        currentTime.value = props.time
        clearInterval(interval)//销毁计时器
    }

    watch(currentTime, (currVal, perVal) => {
        emit('change', currVal)
    })

    onMounted(() => {
        if (props.autoStart) {
            start()
        }
    })
    onBeforeUnmount(() => {
        clearInterval(interval)//销毁计时器
    })

    defineExpose({start, pause, reset})
</script>

<style scoped>

</style>
